import asyncio
from fastapi import APIRouter, Depends, FastAPI
from typing import List
from datetime import datetime, timedelta
import psutil
import random
from starlette.middleware.cors import CORSMiddleware
from uvicorn import lifespan
from app.api.summary import summary_router
from app.api.chart import chart_route
from app.api.ws import wsclient
from app.api.terminal_ws import router as terminal_router
from app.api.chat_ws import router as chat_router
from app.core.background_monitor import background_monitor, process_monitor_task

# 创建FastAPI应用
app = FastAPI(
    title="麒麟系统监控API",
    description="银河麒麟2503SP1系统实时监控服务",
    version="2.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境应该限制具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(summary_router)
app.include_router(chart_route)
app.include_router(wsclient)
app.include_router(terminal_router, prefix="/api")
app.include_router(chat_router, prefix="/api")


# @app.on_event("startup")
# async def startup_event():
#     print("🚀 系统监控API服务已启动")
#     print("✅ 访问 http://localhost:8000/docs 查看API文档")
#     # 启动后台监控任务
#     asyncio.create_task(background_monitor())
#     asyncio.create_task(process_monitor_task())


# 存储后台任务的引用
background_tasks = set()


@app.on_event("startup")
async def startup_event():
    print("🚀 系统监控API服务已启动")
    print("✅ 访问 http://localhost:8000/docs 查看API文档")

    # 创建任务并存储引用
    task1 = asyncio.create_task(background_monitor())
    task2 = asyncio.create_task(process_monitor_task())

    # 将任务添加到集合中以便后续管理
    background_tasks.add(task1)
    background_tasks.add(task2)


@app.on_event("shutdown")
async def shutdown_event():
    print("🛑 系统监控API服务正在关闭...")

    # 取消所有后台任务
    for task in background_tasks:
        task.cancel()

    # 等待所有任务完成取消（忽略取消异常）
    await asyncio.gather(*background_tasks, return_exceptions=True)

    print("✅ 所有后台任务已停止")
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)